Page({
  data: {
    userName: null,
    originPassword: null,
    firstNewPassword: null,
    secondNewPassword: null
  },
  onLoad() {
    wx.getStorage({
      key: "user",
      success: (user) =>{
        this.setData({
          userName: user.data.name
        });
      }
    });
  },
  setOriginPassword(e){
    this.setData({
      originPassword: e.detail.value
    });
  },
  setFirstNewPassword(e) {
    this.setData({
      firstNewPassword: e.detail.value
    });
  },
  setSecondNewPassword(e) {
    this.setData({
      secondNewPassword: e.detail.value
    });
  },

  modifyPassowrd() {
    if(!this.noExistNullValue()) {
      wx.showToast({
        title: '信息不完整',
        icon: "error", 
        duration: 2000,
      });
      return;
    }
    if(!this.passwordIsSame(this.data.firstNewPassword, this.data.secondNewPassword)) {
      wx.showToast({
        title: '密码不一致',
        icon: "error", 
        duration: 2000,
      });
      return;
    }
    if(this.passwordIsSame(this.data.firstNewPassword, this.data.originPassword)) {
      wx.showToast({
        title: "新旧密码一致",
        icon: "error", 
        duration: 2000,
      });
      return;
    }
    if(!this.passwordIsLegal(this.data.firstNewPassword)) {
      wx.showToast({
        title: '密码长度>=6',
        icon: "error", 
        duration: 2000,
      });
      return;
    }
    console.log(this.data.userName);
    // 修改密码
    wx.cloud.database()
            .collection('user')
            .where({
              name: this.data.userName
            })
            .update({
              data: {
                password: this.data.firstNewPassword
              },
              success: () => {
                wx.navigateBack();
                wx.showToast({
                  title: "修改成功",
                  icon: "success",
                  duration: 2000,
                });
              },
              fail: (err) => {
                console.error("修改失败：", err);
                wx.showToast({
                  title: "修改失败",
                  icon: "error",
                  duration: 2000,
                });
              }
            });
  },
  noExistNullValue() {
    for (const key in this.data) {
      if (this.data[key] === null) {
        return false;
      }
    }
    return true;
  },
  passwordIsLegal(password) {
    return password.length >= 6;
  },
  resetInput() {
    this.setData({
      originPassword: null,
      firstNewPassword: null,
      secondNewPassword: null
    });
  },
  passwordIsSame(first, second) {
    return first === second;
  }
})